package com.itheima.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.EmployeeDao;
import com.itheima.pojo.Employee;
import com.itheima.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
@Slf4j
@Service
public class EmployeeServiceImpl extends ServiceImpl<EmployeeDao, Employee> implements EmployeeService {
    @Autowired
    private EmployeeDao employeeDao;
    private final String gensalt = "$2a$10$kxMbhZGH3ud8gijC7.hjtO";
    /**
     * 验证登录
     * @param employee
     * @return
     */
    @Override
    public Map checkLogin(Employee employee, HttpSession session) {
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Employee::getUsername,employee.getUsername());
        Employee employeeLogin = employeeDao.selectOne(lqw);
        Map map = new HashMap<>();
        //1.根据用户名查询用户信息：  select * from user where username=?
        //判断：查询不到，返回登录失败
        if (employeeLogin == null){
            map.put("msg","用户不存在");
            return map;
        }
        //3.判断：用户是否禁用【status：0禁用  1正常】，如果是禁用，返回登录失败【员工已禁用】
        if (employeeLogin.getStatus().equals(0)){
            map.put("msg","登录失败，员工已禁用");
            return map;
        }
        //2.如果查询到了，比对密码是否正确【用户输入的密码加密后和 数据库的密码进行比对】
        //判断： 比对失败，返回登录失败
        if (BCrypt.checkpw(employee.getPassword(),employeeLogin.getPassword())){
            map.put("emp",employeeLogin);
            session.setAttribute("emp",employeeLogin);
            return map;
        }else {
            map.put("msg","登录失败");
            return map;
        }
    }

    @Override
    public int add(Employee employee) {
        employee.setPassword(BCrypt.hashpw("123456",gensalt));
        return employeeDao.insert(employee);
    }

    @Override
    public Page<Employee> pageSelect(Integer page, Integer pageSize, String name) {
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(name != null && !"".equals(name),Employee::getName,name);
        lqw.orderByDesc(Employee::getUpdateTime);
        Page employeePage = new Page<>(page,pageSize);
        employeeDao.selectPage(employeePage,lqw);
        return employeePage;
    }
}
